#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/wait.h>

int main()
{
    int pipefds[2];
    pid_t pid;
    char buffer[80];
    const char *message = "Hello,Pipe!";
    // 创建管道
    if (pipe(pipefds) == -1)
    {
        perror("pipe create error");
        return 1;
    }
    // 创建子进程
    pid = fork();
    if (pid == -1)
    {
        perror("fork error!");
        return 1;
    }

    if (pid == 0)
    {
        // 子进程
        close(pipefds[1]); // 关闭写端
        read(pipefds[0], buffer, sizeof(buffer));
        std::cout << "Child received: " << buffer << std::endl;
        close(pipefds[0]);
        std::cout << "Child pid: " << getpid() << std::endl;
    }
    else
    {
        // 父进程
        close(pipefds[0]); // 关闭读端
        write(pipefds[1], message, strlen(message));
        close(pipefds[1]);
        std::cout << "Father pid: " << getpid() << std::endl;
        wait(NULL); // 等待子进程结束
    }
    return 0;
}